package cn.yeziji.utils;

import cn.yeziji.entity.AliOssConfig;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import lombok.Data;

import java.util.Objects;

/**
 * @author gzkemays
 * @date 2021/2/9 22:16
 */
@Data
public class AliUtils {

  public static String uploadImgToOSS(AliOssConfig config) {
    String endPoint = config.getEndPoint();
    String accessKey = config.getAccessKey();
    String security = config.getSecretKey();
    String savePath =
        config.getSavePath().endsWith("/") ? config.getSavePath() : config.getSavePath() + "/";
    String bucketName = config.getBucketName();
    String ext = Objects.isNull(config.getExt()) ? "" : config.getExt();
    OSS ossClient = new OSSClient(endPoint, accessKey, security);
    String fileName;
    if (Objects.isNull(config.getFileName()))
      fileName = savePath + System.currentTimeMillis() + ext;
    else fileName = savePath + config.getFileName() + ext;
    ossClient.putObject(bucketName, fileName, config.getStream());
    ossClient.shutdown();
    return fileName;
  }
}
